package com.jdk.demo.thread.completableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.BiConsumer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//当CompletableFuture的计算结果完成，或者抛出异常的时候，可以执行特定的Action
//可以看到Action的类型是BiConsumer<? super T,? super Throwable>它可以处理正常的计算结果，或者异常情况。
//whenComplete 和 whenCompleteAsync 的区别：
//whenComplete：是执行当前任务的线程执行继续执行 whenComplete 的任务。
//whenCompleteAsync：是执行把 whenCompleteAsync 这个任务继续提交给线程池来进行执行
public class WhenCompleteDemo {

	private static final Logger log = LoggerFactory.getLogger(WhenCompleteDemo.class);

	public static void main(String[] args) throws InterruptedException {
		ExecutorService executorService = Executors.newFixedThreadPool(2);
        CompletableFuture cf = CompletableFuture.supplyAsync(() -> { //实现了Supplier的get()方法
            try {
                Thread.sleep(2000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            log.info("supplyAsync");
            return "hello ";
        }, executorService)
        .whenComplete(new BiConsumer<String, Throwable>() {
            @Override
            public void accept(String s, Throwable action) {
            	log.info("执行完成！" + s);
            }
        });

        while (true) {
            if (cf.isDone()) {
            	log.info("CompletedFuture...isDown");
                break;
            }
            Thread.sleep(5000);
        }
	}

}
